package com.debao;

import cn.hutool.core.date.DateUtil;
import com.debao.common.constant.Constants;
import com.debao.common.core.domain.AjaxResult;
import com.debao.common.utils.SecurityUtils;
import com.debao.system.domain.*;
import com.debao.system.domain.rsp.SignRsp;
import com.debao.system.domain.vo.SignReqVo;
import com.debao.system.service.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@RequestMapping("/api/signIn")
@RestController
@CrossOrigin
public class ApiSignIn {

    @Resource
    private ISignInService signInService;

    @Resource
    private ICourseCardService courseCardService;

    @Resource
    private ICourseCardOrderService cardOrderService;

    @Resource
    private IAppointService appointService;

    @Resource
    private ICourseTypeService courseTypeService;
    @Resource
    private ITimeUserCardService timeUserCardService;


    /**
     * 用户签到
     *
     * @param
     * @return
     */
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SignRsp signRsp) {
        //判断用户今天是否已经签到
        Boolean isExist = signInService.selectSignInByUserId(signRsp.getUserId(), signRsp.getCourseCardId(),signRsp.getDate());
        if (isExist) {
            return AjaxResult.error("该用户今日已签到过了");
        }
        Appoint appoint = appointService.selectAppointByAId(signRsp.getAppointId(), signRsp.getDate(),signRsp.getStartAt(),signRsp.getEndAt());
        if (appoint == null) {
            throw new RuntimeException("用户排期不存在");
        }
        // 更新排期表的状态
        // 判断排期的状态是否为已确认未签到
        if (appoint.getStatus().equals(Constants.SIGNED_IN_1)) {
            appoint.setStatus(Constants.SIGNED_IN_2);
            int updateResult = appointService.updateAppoint(appoint);
            if (updateResult != 1) {
                throw new RuntimeException("更新排期状态失败");
            }
        }
        //签到
        int row = signInService.insertSignIn(new SignIn().setCoachId(signRsp.getCoachId()).setUserId(signRsp.getUserId()).setImage(signRsp.getImage()).setCourseCardId(signRsp.getCourseCardId()).setDate(DateUtil.today()));
        if (row == 1) {
            return AjaxResult.success("签到成功");
        }
        return AjaxResult.error("签到失败");
    }

    /**
     * 查看我学员今日签到列表
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam Long coachId, @RequestParam Long cardId) {
        List<SignIn> signIns = signInService.selectSignInList(new SignIn().setCoachId(coachId).setCourseCardId(cardId).setDate(DateUtil.today()));
        return AjaxResult.success(signIns);
    }
}
